package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Resource
    private EmpMapper empMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpExprService empExprService;

    //查询员工列表
    @Override
    public PageResult<Emp> empPage(EmpQueryParam param) {
        //设置页码，每页几条数据
        Page<Emp> empPage = Page.of(param.getPage(), param.getPageSize());
        //设置排序条件
        empPage.addOrder(OrderItem.desc("entry_date"));
        QueryWrapper<Emp> wrapper = Wrappers.<Emp>query().like(param.getName() != null && !param.getName().isEmpty(), "name", param.getName())
                .eq(param.getGender() != null, "gender", param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, "entry_date", param.getBegin(), param.getEnd());
        empPage = page(empPage, wrapper);
        List<Emp> empList = empPage.getRecords();
        if (empList != null && !empList.isEmpty()) {
            //补全部门名称数据
            //1、获取当前页面所有员工部门id
            Set<Integer> ids = empList.stream().map(Emp::getDeptId).collect(Collectors.toSet());
            //2、根据id查询部门名称
            List<Dept> deptList = deptMapper.selectBatchIds(ids);
            //3、转换成map集合
            Map<Integer, String> map = deptList.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
            //4、补全每个员工的部门名称
            for (Emp emp : empList) {
                emp.setDeptName(map.get(emp.getDeptId()));
            }

            return new PageResult<>(empPage.getTotal(), empList);
        }
        return null;
    }

    //新增员工
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {

        //    保存员工数据
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        save(emp);
        //    保存员工工作经历数据
        List<EmpExpr> empExprList = emp.getExprList();
        if (empExprList != null) {
            empExprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.saveBatch(empExprList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        lambdaUpdate().eq(Emp::getId, emp.getId()).update(emp);
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && !exprList.isEmpty()) {
            List<EmpExpr> empExprList = empExprService.lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()).list();
            empExprService.removeBatchByIds(empExprList);
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmpByIds(List<Integer> ids) {
        removeBatchByIds(ids);
        List<EmpExpr> empExprList = empExprService.lambdaQuery().in(EmpExpr::getEmpId, ids).list();
        if (empExprList != null && !empExprList.isEmpty()) {
            empExprService.removeBatchByIds(empExprList);
        }
    }

}
